import json
from dataclasses import dataclass, field, asdict
from typing import List, Dict

import toml


@dataclass
class Task:
    name: str = '策略'
    symbols: List[str] = field(default_factory=list)

    start_date: str = '20100101'
    end_date: str = None

    benchmark: str = '510300.SH'
    select: str = 'SelectAll'

    select_buy: List[str] = field(default_factory=list)
    buy_at_least_count: int = 0
    select_sell: List[str] = field(default_factory=list)
    sell_at_least_count: int = 1

    order_by_signal: str = ''
    order_by_topK: int = 1
    order_by_dropN: int = 0
    order_by_DESC: bool = True  # 默认从大至小排序

    weight: str = 'WeighEqually'
    weight_fixed: Dict[str, int] = field(default_factory=dict)
    period: str = 'RunDaily'
    period_days: int = None

def json_to_task(json_str: str) -> Task:
    """将 JSON 字符串转换为 Task 实例"""
    data = json.loads(json_str)
    return Task(**data)

def task_to_toml(task: Task) -> str:
    """将 Task 实例转换为 TOML 字符串"""
    return toml.dumps(asdict(task))


from dataclasses import fields, is_dataclass
from typing import Dict, Any


def dict_to_task(data: Dict[str, Any]) -> Task:
    """将字典安全转换为 Task 实例"""
    # 获取 Task 类的字段集合
    valid_fields = {f.name for f in fields(Task)}

    # 过滤非法字段并进行类型检查
    filtered_data = {}
    for key, value in data.items():
        if key not in valid_fields:
            continue

        # 获取字段类型信息
        field_type = Task.__annotations__.get(key)

        # # 简单类型校验（可选）
        # if field_type and not isinstance(value, field_type):
        #     try:
        #         # 尝试类型转换（如 str -> List）
        #         value = field_type(value)
        #     except (TypeError, ValueError):
        #         raise ValueError(
        #             f"字段 '{key}' 类型不匹配，预期 {field_type}，实际 {type(value)}"
        #         )

        filtered_data[key] = value

    return Task(**filtered_data)